const express = require('express');
const cors = require('cors');
const { verifyToken } = require('./utils/auth');
const path = require('path');
const sequelize = require('./config/db'); // 确保路径正确
const userRoute = require('./routes/userRoute');
const goodsRoute = require('./routes/goodsRoute');
const typeRoute = require('./routes/typeRoute');
const commonRoute = require('./routes/commonRoute');
const tagRoute = require('./routes/tagRoute');
const recommendRoute = require('./routes/recommendRoute');
const neo4jDriver = require('./config/neo4j');

const app = express();

//静态代理
app.use('/static', express.static(path.join(__dirname, 'static')));

// 测试数据库连接
sequelize.authenticate()
  .then(() => console.log('数据库连接成功'))
  .catch(err => console.error('数据库连接失败:', err));

// 中间件配置
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 添加Neo4j中间件
app.use((req, res, next) => {
  req.neo4j = neo4jDriver;
  next();
});

// 修改数据库中间件
app.use((req, res, next) => {
  req.db = sequelize; // 使用sequelize实例
  next();
});

// 认证中间件 - 验证JWT令牌
const authMiddleware = (req, res, next) => {
  const token = req.headers['authorization'];
  if (!token) {
    return res.send({ message: '未提供认证令牌', code: 401 });
  }
  try {
    const decoded = verifyToken(token); // 验证并解码令牌
    req.user = decoded; // 将解码后的用户信息附加到请求对象
    next();
  } catch (err) {
    // 捕获令牌过期或无效错误
    return res.send({ message: '令牌无效或已过期',  code: 401 });
  }
};

//路由配置
app.use('/user', userRoute); // 用户相关路由
app.use('/goods', authMiddleware, goodsRoute);
app.use('/type', authMiddleware, typeRoute);
app.use('/tag', authMiddleware, tagRoute);
app.use('/recommend', authMiddleware, recommendRoute);
app.use('/common',  commonRoute); // 公共方法

// 在服务器启动时同步模型
app.listen(3000, async () => {
  try {
    await sequelize.sync(); // 自动同步所有模型
    console.log('Server is running on port 3000');
    console.log('数据库模型已同步');
    // 在数据库连接后添加(在sequelize ORM中做表关系映射)
    require('./models/associations');
  } catch (err) {
    console.error('模型同步失败:', err);
  }
});
